package org.example.paymentservice.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.paymentservice.service.WebhookHandler;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/payments/webhook")
@RequiredArgsConstructor
public class PaymentWebhookController {
    private final Map<String, WebhookHandler> webhookHandlers;

    @PostMapping("/wechat")
    public ResponseEntity<String> handleWeChatPayWebhook(
            @RequestBody String payload,
            HttpServletRequest request) {
        try {
            WebhookHandler handler = webhookHandlers.get("wechat_pay_webhook");
            Map<String, String> headers = extractHeaders(request);
            
            handler.handlePaymentNotification(payload, headers);
            
            // 返回微信支付要求的格式
            return ResponseEntity.ok("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
        } catch (Exception e) {
            log.error("Failed to process WeChatPay webhook", e);
            return ResponseEntity.ok("<xml><return_code><![CDATA[FAIL]]></return_code></xml>");
        }
    }

    @PostMapping("/alipay")
    public ResponseEntity<String> handleAliPayWebhook(
            @RequestParam Map<String, String> params,
            HttpServletRequest request) {
        try {
            WebhookHandler handler = webhookHandlers.get("alipay_webhook");
            Map<String, String> headers = extractHeaders(request);
            
            handler.handlePaymentNotification(JsonUtil.toJson(params), headers);
            
            // 返回支付宝要求的格式
            return ResponseEntity.ok("success");
        } catch (Exception e) {
            log.error("Failed to process AliPay webhook", e);
            return ResponseEntity.ok("fail");
        }
    }

    private Map<String, String> extractHeaders(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.put(headerName, request.getHeader(headerName));
        }
        return headers;
    }
}